package MainTest;

import java.util.HashSet;

/**
 * Created by xuyi on 2017/2/14.
 */
public class EntryNodeOfLoop {

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }

    public static void main(String[] args) {
        ListNode listNode1 = new EntryNodeOfLoop().new ListNode(1);
        ListNode listNode2 = new EntryNodeOfLoop().new ListNode(2);
        ListNode listNode3 = new EntryNodeOfLoop().new ListNode(3);
        ListNode listNode4 = new EntryNodeOfLoop().new ListNode(4);
        ListNode listNode5 = new EntryNodeOfLoop().new ListNode(5);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        listNode4.next = listNode5;
        listNode5.next = listNode3;

        Solution solution = new EntryNodeOfLoop().new Solution();
        ListNode listNode = solution.EntryNodeOfLoop(listNode1);

        System.out.println(listNode.val);
    }

    public class Solution {

        public ListNode EntryNodeOfLoop(ListNode pHead) {

            HashSet<ListNode> listNodes = new HashSet<>();
            listNodes.add(pHead);
            ListNode target = null;
            while (pHead.next != null) {
                pHead = pHead.next;
                if (listNodes.contains(pHead)) {
                    target = pHead;
                    break;
                } else {
                    listNodes.add(pHead);
                }
            }
            return target;
        }
    }


}
